package com.otod.commons.filemanger;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.otod.base.exception.AppException;
import com.otod.commons.constants.AttachmentConstant;
import com.otod.commons.utils.StringUtils;


/**
 * 读取Excel导入配置文件
 * 
 * @author jqiu
 * 
 */
public class ExcelImportCfgInit {
	private static Logger logger = LoggerFactory.getLogger(ExcelImportCfgInit.class);
	
	private static Map<String,Map<String,Object>> cfgMap = new HashMap<String, Map<String,Object>>();
	private String path;

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	/**
	 * 初始化读取配置文件
	 */
	public void init() {
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
		Document doc;
		Resource[] resources;
		try {
			resources = resourcePatternResolver.getResources(this.path);
			if (resources == null) {
				return;
			}
			for (int i = 0; i < resources.length; ++i) {
				doc = initXmls(resources[i].getURL());
			}
		} catch (IOException e) {
			logger.error("Excel导入配置", e);
		} catch (AppException e) {
			logger.error(e.getMsg());
		}
	}
	
	/**
	 * 获Excel导入配置
	 * @param cfgCode
	 * @return			Map<String,Object>
	 * @throws AppException
	 */
	public static Map<String,Object> getCfg(String cfgCode) throws AppException{
		if(cfgMap == null || cfgMap.get(cfgCode)==null){
			throw new AppException("E_TL_0000030");												/*配置不存在*/
		}
		return cfgMap.get(cfgCode);
	}

	/**
	 * 获取配置文件
	 * @param fileUrl 	配置文件路径
	 * @return dom4j 	Document
	 * @throws AppException
	 */
	protected Document initXmls(URL fileUrl) throws AppException{
		Document document = null;
		try {
			document = new SAXReader().read(fileUrl).getDocument();
			initDoc(document);
		} catch (DocumentException e) {
			logger.error(fileUrl.getPath()+"读取失败！", e);
			throw new AppException(fileUrl.getPath()+"读取失败！");		
		}
		return document;
	}

	/**
	 * 循环解析xml，读取的配置放入map中
	 * @param document
	 * @throws AppException
	 */
	protected void initDoc(Document document) throws AppException{
		Map<String,Object> curCfgMap;
		String sheetName,sheetNumStr;
		int sheetNum,firstContentRowNum,firstColumNum,headerRowNum;
		for (Element template : (List<Element>) document.getRootElement().elements()) {
			curCfgMap = new HashMap<String, Object>();
//			if(cfgCode.equals(template.attributeValue("name"))){
				Map<String, Object> baseAttrMap = new HashMap<String, Object>();				/*基础属性Map*/
				sheetName = template.attributeValue("sheetName");
				if(StringUtils.isEmpty(sheetName)){
					sheetNumStr = template.attributeValue("sheetNum");
					if(StringUtils.isEmpty(sheetNumStr)){
						throw new AppException("E_TL_0000023");										/*未配置工作表*/
					}else{
						sheetNum = StringUtils.getInt(sheetNumStr, 0)-1;
						if(sheetNum<0){
							throw new AppException("E_TL_0000024");									/*工作表num配置不正确*/
						}
					}
					baseAttrMap.put("sheetNum", sheetNum);
				}else{
					baseAttrMap.put("sheetName", sheetName);
				}
				
				headerRowNum = StringUtils.getInt(template.attributeValue("headerRowNum"),0)-1;					/*转换为poi使用的行数*/
				if(headerRowNum<0){
					throw new AppException("E_TL_0000025");											/*表头位置配置不正确*/
				}
				baseAttrMap.put("headerRowNum",headerRowNum);
				
				if(template.attributeValue("firstContentRowNum") == null){
					firstContentRowNum = headerRowNum + 1;
				}else{
					firstContentRowNum = StringUtils.getInt(template.attributeValue("firstContentRowNum"),0)-1;	/*转换为poi使用的行数*/
					if(firstContentRowNum<0){
						throw new AppException("E_TL_0000026");										/*第一行内容位置配置不正确*/
					}
				}
				baseAttrMap.put("firstContentRowNum",firstContentRowNum);
				
				
				List<Map<String,String>> colList = new ArrayList<Map<String,String>>();
				Map<String,String> keyLabelMap = new HashMap<String, String>();
				
				for (Element column : (List<Element>)((Element)(template.elements().get(0))).elements()){
					Map<String, String> colAttrMap = new HashMap<String, String>();				/*key Label Map*/
					if(StringUtils.isEmpty(column.attributeValue("key")) || StringUtils.isEmpty(column.attributeValue("label"))){
						throw new AppException("E_TL_0000026");										/*..参数不能为空*/
					}
					colAttrMap.put("key", column.attributeValue("key"));
					colAttrMap.put("label", column.attributeValue("label"));
					colAttrMap.put("type", column.attributeValue("type")==null?"string":column.attributeValue("type"));
					colAttrMap.put("required", column.attributeValue("required")==null?"false": column.attributeValue("required"));
					colList.add(colAttrMap);
					keyLabelMap.put(column.attributeValue("key"), column.attributeValue("label"));
				}
				if(colList.size()==0){
					throw new AppException("E_TL_0000028");											/*列数不能不配置*/
				}
				if(keyLabelMap.size() != colList.size()){
					throw new AppException("E_TL_0000029");											/*cfgCode key有重复*/
				}
				
				curCfgMap.put("baseAttr", baseAttrMap);
				curCfgMap.put("cols", colList);
				curCfgMap.put(AttachmentConstant.EXCEL_KEYLABELMAP, keyLabelMap);
				
				cfgMap.put(template.attributeValue("name"), curCfgMap);
//				break;
//			}
		}
	}
}
